#!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# Copyright (C) 2007 Ville Leskinen
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA

"""This module provides classes and functions for configuration of igCreator"""

import ConfigParser

from optparse import OptionParser
from __init__ import __version__

def GenerateConfig(configs):
	"""Generates one L{igCreator.config.Config} object from given configs. The
	configs-parameter is a list containing L{igCreator.config.Config} objects
	that are read so that first object overrides the second, the second
	overrides the third and so on.

	@param configs: list of configs
	@type configs: list
	@return: the final configuration"""
	config = Config()
	configs.reverse() # we have to reverse the list to get it in right order
	for c in configs:
		for opt, var in c.config.iteritems():
			if var:
				config.config[opt] = var

	return config
				
	

class Config(object):
	"""Base class for configs. Does basicly nothing."""
	def __init__(self):
		self.config = { 'imagedir' : None,
						'images' : None,
						'outputdir' : None,
						'size' : None,
						'thumbsize': None,
						'pictemplate' : None,
						'thumbtemplate' : None,
						'filter' : None,
						'heading' : None,
						'custom-css': None,
						'verbose': None }

	def __str__(self):
		s = ""
		for option, var in self.config.iteritems():
			if var:
				s += "%s=%s\n" % (option, var)

		return s
	

class CfgFileConfig(Config):
	"""Creates a config from configuration files."""

	def __init__(self, paths):
		"""Constructor. The paths-parameter can be either list or a string.

		@param paths: path(s) to the configuration file(s)
		@type paths: string or list"""
		Config.__init__(self)
		self.cfg = ConfigParser.ConfigParser()
		self.cfg.read(paths)
		self._createConfig()

	def _createConfig(self):
		for option, var in self.config.iteritems():
			s = "default" # section
			if self.cfg.has_option(s, option):
				if option == "verbose":
					value = self.cfg.get(s,option)
					if value == "True":
						self.config['verbose'] = True
					elif value == "False":
						self.config['verbose'] = False
					elif value != None:
						print "Invalid config option %s: %s. Ignoring." % (option, value)

				self.config[option] = self.cfg.get(s, option)
	
class CmdLineConfig(Config):
	"""Handels command line options. Compared to other classes derived from
	L{igCreator.config.Config} this class has special option 'configfile'."""
	def __init__(self, args):
		"""Constructor

		@param args: list of command line options
		@type args: list"""
		Config.__init__(self)
		self._initParser()
		(self.options, self.args) = self.parser.parse_args()
		self._createConfig()

	def _initParser(self):
		usage = "%prog [options] [-o DIR] image1 image2 ..."
		self.parser = OptionParser(usage=usage,
			version="%prog " + __version__)

		self.parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
			help="more verbose output")

		self.parser.add_option("-c", "--configfile", dest="configfile",
			metavar="FILE",
			help="use configuration file FILE")

		self.parser.add_option("-d", "--imagedir", dest="imagedir",
			metavar="PATH",
			help="use images from PATH to create the gallery")

		self.parser.add_option("-o", "--outputdir", dest="outdir",
			metavar="PATH",
			help="create the gallery to given PATH")

		self.parser.add_option("-s", "--size", dest="size",
			help="specify size for images in gallery(--size=help for possible values)")

		self.parser.add_option("-t", "--thumbsize", dest="thumbsize",
			metavar="SIZE",
			help="same as -size but for thumbnails")

		self.parser.add_option("-p", "--pictemplate", dest="pictemplate",
			metavar="FILE",
			help="instead of default picture template use FILE")

		self.parser.add_option("-T", "--thumbtemplate", dest="thumbtemplate",
			metavar="FILE",
			help="instead of defeault thumbnail template use FILE")

		self.parser.add_option("-f", "--filter", dest="resizefilter",
			metavar="FILTER",
			help="specify a filter used in image resizing(--filter=help for possible values)")

		self.parser.add_option("-H", "--heading", dest="heading", metavar="STRING",
			help="heading for the thumbnail page")

		self.parser.add_option("--custom-css", dest="custom_css", metavar="FILE",
			help="use custom css-file instead of the default one")

		
	def _createConfig(self):
		self.configfile = self.options.configfile
		self.config['imagedir'] = self.options.imagedir
		self.config['images'] = self.args
		self.config['outputdir'] = self.options.outdir
		self.config['size'] = self.options.size
		self.config['thumbsize'] = self.options.thumbsize
		self.config['pictemplate'] = self.options.pictemplate
		self.config['thumbtemplate'] = self.options.thumbtemplate
		self.config['filter'] = self.options.resizefilter
		self.config['heading'] = self.options.heading
		self.config['custom-css'] = self.options.custom_css
		self.config['verbose'] = self.options.verbose
			

